// ffprobe-static-prune/index.js
const fs = require('fs');
const path = require('path');

const archMap = {
  x64: 'x64',
  ia32: 'ia32',
  arm: 'armv7l',
  arm64: 'arm64',
};

function pruneFFprobe({ baseDir, platform, arch }) {
  const resolvedArch = archMap[arch];
  if (!resolvedArch) {
    throw new Error(`Unsupported arch: ${arch}`);
  }

  const ffprobeBase = path.join(baseDir, 'node_modules', 'ffprobe-static', 'bin');
  const keepPath = path.join(ffprobeBase, platform, resolvedArch);

  if (!fs.existsSync(keepPath)) {
    console.warn(`⚠ [ffprobe-static-prune] Keep path not found: ${keepPath}`);
    return;
  }

  for (const platformDir of fs.readdirSync(ffprobeBase)) {
    const platformPath = path.join(ffprobeBase, platformDir);
    if (!fs.statSync(platformPath).isDirectory()) continue;

    for (const archDir of fs.readdirSync(platformPath)) {
      const targetPath = path.join(platformPath, archDir);
      if (targetPath !== keepPath) {
        console.log(`❌ [ffprobe-static-prune] Removing: ${targetPath}`);
        fs.rmSync(targetPath, { recursive: true, force: true });
      }
    }

    // If platform dir is now empty, remove it
    if (platformPath !== path.dirname(keepPath)) {
      try {
        fs.rmdirSync(platformPath);
      } catch (_) {}
    }
  }

  console.log(`✅ [ffprobe-static-prune] Finished: kept ${keepPath}`);
}

module.exports = pruneFFprobe;

if (require.main === module) {
  const args = require('minimist')(process.argv.slice(2));
  const baseDir = args.baseDir || process.cwd();
  const platform = args.platform || process.platform;
  const arch = args.arch || process.arch;

  pruneFFprobe({ baseDir, platform, arch });
}


// node index.js --platform=darwin --arch=arm64 --baseDir=/your/project/path
